package com.archeocs.figone.gui;

//Author:
//Miłosz Pigłas, Archeocs milosz@archeocs.com
//
//Copyright (c) 2010, Miłosz Pigłas, Archeocs
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//* Neither the name of the [ORGANIZATION] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import com.archeocs.figone.lib.Uklad;

/**
 * Okno dialogowe, w ktorym wyswietlane sa poszczegolne uklady
 * @author Milosz Piglas
 *
 */
public class Widok extends javax.swing.JDialog {
	
	private static final long serialVersionUID = -6315023860446949871L;
	private static Widok dialog;
	private JButton btnNastepny, btnRozmiar, btnZapisz, btnZamknij;
    private JToolBar tbPrzyciski;
	private JScrollPane jScrollPane1;
	private JLabel jab;
	private Uklad uklad;
	private BufferedImage img;
	private JButton btnZapamietaj;
	private boolean pomniejsz = false;
	private static int rodzaj = 0;

	/**
	 * Konstruktor okna. 
	 * @param parent
	 * @param modal
	 * @param uklad 
	 */
    private Widok(java.awt.Frame parent, boolean modal, Uklad uklad) {
        super(parent, modal);
        this.uklad = uklad;
        this.uklad.nowyUklad(rodzaj);
        img = this.uklad.getNowy();
        widokInit();
    }
    
    /**
     * Wyswietla w oknie nowy uklad
     * @param pomniejsz jesli true uklad jest pomniejszony o 50%
     */
    private void wyswietl(boolean pomniejsz)
    {
    	int w, h;
    	if (pomniejsz)
    	{
    		w = (int)(img.getWidth()*0.5);
    		h = (int)(img.getHeight()*0.5);
    		jab.setIcon(new ImageIcon(img.getScaledInstance(w, h, Image.SCALE_DEFAULT)));
    	}
    	else
    	{
    		w = img.getWidth()-20;
    		h = img.getHeight()-20;
    		jab.setIcon(new ImageIcon(img));
    	}
    	setSize(w+100, h+100);
    	jScrollPane1.setSize(w+60, h+60);
    	setTitle(uklad.naglowek);
    }
    
    /**
     * Zapisuje uklad w formacie PNG we wskazanej lokalizacji
     */
    private void zapiszObrazek()
    {
    	JFileChooser fcDialog = new JFileChooser();
    	int ret = fcDialog.showSaveDialog(this);
    	if (ret == JFileChooser.APPROVE_OPTION)
    	{
    		File doZapisu = fcDialog.getSelectedFile();
    		try {
				ImageIO.write(img, "png", doZapisu);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    }

    private void widokInit() {

        tbPrzyciski = new JToolBar();
        btnNastepny = new JButton("Następny");
        btnRozmiar = new JButton("100%");
        btnZapisz = new JButton("Zapisz");
        btnZamknij = new JButton("Zamknij");
        btnZapamietaj = new JButton("Zapamietaj");

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        /*
         * Obsluga zdarzen
         */
        ActionListener nastepny_click = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				btnRozmiar.setText("100%");
				pomniejsz = false;
				uklad.nowyUklad(rodzaj);
				img = uklad.getNowy();
				wyswietl(true);
			}
        	
        };
        
        KeyAdapter nastepny_key = new KeyAdapter()
        {
        	public void keyReleased(KeyEvent k)
        	{
        		if (k.getKeyCode() == KeyEvent.VK_SPACE)
        		{
        			btnRozmiar.setText("100%");
    				pomniejsz = false;
        			uklad.nowyUklad(rodzaj);
    				img = uklad.getNowy();
    				wyswietl(true);
        		}
        	}
        };
        
        ActionListener zapisz_click = new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent e) {
				zapiszObrazek();				
			}
        	
        };
        
        KeyAdapter zapisz_key = new KeyAdapter() 
        {
        	public void keyPressed(KeyEvent k)
        	{
        		if (k.getModifiersEx() == InputEvent.CTRL_DOWN_MASK && k.getKeyCode() == KeyEvent.VK_S)
        			zapiszObrazek();
        	}
        };
        
        ActionListener rozmiar_click = new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (pomniejsz)
				{
					btnRozmiar.setText("100%");
					wyswietl(pomniejsz);
					pomniejsz = !pomniejsz;
				}
				else
				{
					btnRozmiar.setText("50%");
					wyswietl(pomniejsz);
					pomniejsz = !pomniejsz;
				}
			}
        	
        };
        
        KeyAdapter rozmiar_key = new KeyAdapter()
        {
        	public void keyReleased(KeyEvent k)
        	{
        		if (k.getKeyCode() == KeyEvent.VK_PAGE_UP)
        		{
        			wyswietl(false);
        			btnRozmiar.setText("50%");
        		}
        		else if (k.getKeyCode() == KeyEvent.VK_PAGE_DOWN)
        		{
        			wyswietl(true);
        			btnRozmiar.setText("100%");
        		}
        	}
        };
        
        ActionListener zamknij_click = new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
        	
        };
        
        KeyAdapter zamknij_key = new KeyAdapter() 
        {
        	public void keyReleased(KeyEvent k)
        	{
        		if (k.getKeyCode() == KeyEvent.VK_ESCAPE)
        			dispose();
        	}
        };
        
        ActionListener zapamietaj_click = new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				uklad.zapamietaj();
			}
        	
        };
        
        KeyAdapter zapamietaj_key = new KeyAdapter() 
        {
        	public void keyPressed(KeyEvent k)
        	{
        		if (k.getModifiersEx() == InputEvent.CTRL_DOWN_MASK && k.getKeyCode() == KeyEvent.VK_M)
        			uklad.zapamietaj();
        	}
        };
       
        tbPrzyciski.setRollover(true);
        btnNastepny.setFocusable(false);
        btnNastepny.setHorizontalTextPosition(SwingConstants.CENTER);
        btnNastepny.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnNastepny.addActionListener(nastepny_click);
        tbPrzyciski.add(btnNastepny);

        btnRozmiar.setFocusable(false);
        btnRozmiar.setHorizontalTextPosition(SwingConstants.CENTER);
        btnRozmiar.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnRozmiar.addActionListener(rozmiar_click);
        tbPrzyciski.add(btnRozmiar);

        btnZapisz.setFocusable(false);
        btnZapisz.setHorizontalTextPosition(SwingConstants.CENTER);
        btnZapisz.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnZapisz.addActionListener(zapisz_click);
        tbPrzyciski.add(btnZapisz);
        
        btnZapamietaj.setFocusable(false);
        btnZapamietaj.setHorizontalTextPosition(SwingConstants.CENTER);
        btnZapamietaj.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnZapamietaj.addActionListener(zapamietaj_click);
        tbPrzyciski.add(btnZapamietaj);
        
        btnZamknij.setFocusable(false);
        btnZamknij.setHorizontalTextPosition(SwingConstants.CENTER);
        btnZamknij.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnZamknij.addActionListener(zamknij_click);
        tbPrzyciski.add(btnZamknij);
        
        jScrollPane1 = new JScrollPane();
        jab = new JLabel();
        jScrollPane1.setViewportView(jab);
        jScrollPane1.setVisible(true);
        jab.setVisible(true);
        
        this.addKeyListener(nastepny_key);
        this.addKeyListener(zapisz_key);
        this.addKeyListener(rozmiar_key);
        this.addKeyListener(zamknij_key);
        this.addKeyListener(zapamietaj_key);
        
        wyswietl(true);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(tbPrzyciski, GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tbPrzyciski, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }
    
    /**
     * Wyświetla okno dialogowe w ktorym generowane sa kolejne uklady rycin
     * @param uklad
     * @param r - rodzaj ukladu.
     */
    public static void showWidok(Uklad uklad, int r)
    {
    	dialog = new Widok(null,true,uklad);
    	rodzaj = r;
    	dialog.setVisible(true);
    }

}
